/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.planning;

import cn.ac.nercis.pes.common.constant.knowledge.TargetType;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.spreadsheet.planning.EvaluationRequireSheetView;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.EvaluationRequireViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.model.dto.project.SystemProcessDTO;
import cn.ac.nercis.pes.model.dto.target.LayerTargetDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationRequireService;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import cn.ac.nercis.pes.service.project.SystemTargetService;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 测评配合需求管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvaluationRequireController implements Initializable, InitEvalDataLoad, GlobalEventHandle {

    @FXML
    private StackPane page;
    @FXML
    private BorderPane bodyPane;
    @FXML
    private ListView<MenuVO> tecMenus;
    @FXML
    private ListView<MenuVO> manageMenus;

    @FXML
    private Label titleLbl;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;
    @FXML
    private EvaluationRequireSheetView sheetView;

    private final SystemTargetService systemTargetService;
    private final EvaluationRequireService evaluationRequireService;

    private final SystemProcessService systemProcessService;

    private final List<LayerTargetDTO> layerTargets = new ArrayList<>();
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    private String currentSystemId;
    private LayerTargetDTO currentLayerTarget;
    private final BooleanProperty enablePaste = new SimpleBooleanProperty(false);

    public EvaluationRequireController() {
        this.systemTargetService = SpringUtils.getBean(SystemTargetService.class);
        this.evaluationRequireService = SpringUtils.getBean(EvaluationRequireService.class);
        this.systemProcessService = SpringUtils.getBean(SystemProcessService.class);
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        this.initMenuControl();
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化测评配合需求信息...");
        this.currentSystemId = systemId;
        this.loadMenuData();
        this.sheetView.initialize(systemId,this::onDeleteEvaluationRequire);
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSave(false,false);
    }

    @FXML
    public void onTmpSave() {
        LogUtils.info(log, "执行暂存操作...");
        this.batchSave(false,false);
    }

    @FXML
    public void onFinishSave() {
        LogUtils.info(log, "执行保存操作...");
        this.batchSave(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSave(true,false);
    }

    public void loadMenuState() {
        LogUtils.info(log, "获取测评进度信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> systemProcessService.findEvaRequireProcess(this.currentSystemId))
                .thenAccept(res->Platform.runLater(()->initMenuEvalState(res)))
                .exceptionally((ex) -> {
                    log.error("获取测评进度信息出错!", ex);
                    return null;
                });
    }

    private void initMenuControl() {
        tecMenus.setCellFactory(listView -> new MenuListCell(true));
        tecMenus.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        manageMenus.getSelectionModel().clearSelection();
                        this.loadPageContent(newValue);
                    }
                });

        manageMenus.setCellFactory(listView -> new MenuListCell(true));
        manageMenus.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        tecMenus.getSelectionModel().clearSelection();
                        this.loadPageContent(newValue);
                    }
                });
    }

    private void loadMenuData() {
        LogUtils.info(log, "获取层面指标信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> systemTargetService.findLayerTarget(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        this.initMenuData(res.getData());
                        this.loadMenuState();
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL)
                                .withMessage("获取指标数据失败！")
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("获取层面指标信息出错!", ex);
                    return null;
                });
    }

    private void initMenuData(List<LayerTargetDTO> targets){
        layerTargets.clear();
        tecMenus.getItems().clear();
        manageMenus.getItems().clear();
        layerTargets.addAll(targets);
        targets.stream().filter(t -> t.getType() == TargetType.TECHNOLOGY)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt -> tecMenus.getItems().add(new MenuVO(1,lt.getTargetId(),lt.getName(),"none-process-icon")));

        targets.stream().filter(t -> t.getType() == TargetType.MANAGEMENT)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt -> manageMenus.getItems().add(new MenuVO(2,lt.getTargetId(),lt.getName(),"none-process-icon")));
        tecMenus.getSelectionModel().select(0);
    }

    private void initMenuEvalState(List<SystemProcessDTO> systemProcess){
        var res = systemTargetService.findLayerTarget(this.currentSystemId).getData();
        AtomicBoolean hasChange = new AtomicBoolean(false);
        tecMenus.getItems().forEach(tm->{
            var finishState = systemProcess.stream()
                    .filter(sp-> StringUtils.contains(sp.getName(),tm.getTitle()))
                    .map(SystemProcessDTO::getFinishState)
                    .findFirst().orElse(FinishState.NONE);
            tm.setIcon(ControlUtils.finishStateToIcon(finishState));
            tm.setState(finishState);
            tm.setError(hasNotApply(tm.getTitle(),res));
            hasChange.set(true);
        });
        if(hasChange.get()){
            tecMenus.refresh();
            hasChange.set(false);
        }
        manageMenus.getItems().forEach(mm->{
            var finishState = systemProcess.stream()
                    .filter(sp-> StringUtils.contains(sp.getName(),mm.getTitle()))
                    .map(SystemProcessDTO::getFinishState)
                    .findFirst().orElse(FinishState.NONE);
            mm.setIcon(ControlUtils.finishStateToIcon(finishState));
            mm.setState(finishState);
            mm.setError(hasNotApply(mm.getTitle(),res));
            hasChange.set(true);
        });
        if(hasChange.get()){
            manageMenus.refresh();
        }
    }

    private boolean hasNotApply(String name,List<LayerTargetDTO> targets){
        return targets.stream()
                .filter(t->StringUtils.equals(t.getName(),name))
                .map(LayerTargetDTO::getExistNotApply)
                .findFirst().orElse(false);
    }

    private void loadPageContent(MenuVO layerMenu){
        currentLayerTarget = this.layerTargets
                .stream()
                .filter(lt->StringUtils.equals(lt.getName(),layerMenu.getTitle()))
                .findFirst()
                .orElse(null);
        if(Objects.isNull(currentLayerTarget)){
            return;
        }
        this.sheetView.setLayerTargetId(currentLayerTarget.getTargetId());
        this.titleLbl.setText(currentLayerTarget.getName());
        this.queryEvaluationRequire();
    }

    private void queryEvaluationRequire() {
        LogUtils.info(log, "获取测评配合需求信息...");
        LogUtils.record(log, "请求数据，systemId:{}，filter:{}", this.currentSystemId, currentLayerTarget.getTargetId());
        CompletableFuture.supplyAsync(() -> this.evaluationRequireService.findEvaluationRequires(this.currentSystemId,
                        currentLayerTarget.getTargetId()))
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(EvaluationRequireViewMapper.INSTANCE::toVO)
                            .toList();
                    sheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取测评配合需求信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL)
                            .withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    private void onDeleteEvaluationRequire(Set<String> ids){
        LogUtils.info(log, "执行删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前测评配合需求信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            deleteEvaluationRequire(ids);
        });
    }

    private void deleteEvaluationRequire(final Set<String> ids) {
        LogUtils.info(log, "删除测评配合需求信息...");
        LogUtils.record(log, "请求数据:{}", ids);
        CompletableFuture.supplyAsync(() -> evaluationRequireService.batchDeleteEvaluationRequires(ids))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.queryEvaluationRequire();
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.SUCCESS).withMessage("删除成功")
                                .build().show();
                        refreshFinishState(FinishState.INCOMPLETE);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("删除测评配合需求信息出错!", ex);
                    return null;
                });
    }

    private void refreshFinishState(FinishState state){
        tecMenus.getItems().stream()
                .filter(m->StringUtils.equals(m.getTitle(),currentLayerTarget.getName()))
                .findFirst()
                .ifPresent(menu->{
                    menu.setIcon(ControlUtils.finishStateToIcon(state));
                    menu.setState(state);
                    tecMenus.refresh();
                });
        manageMenus.getItems().stream()
                .filter(m->StringUtils.equals(m.getTitle(),currentLayerTarget.getName()))
                .findFirst()
                .ifPresent(menu->{
                    menu.setIcon(ControlUtils.finishStateToIcon(state));
                    menu.setState(state);
                    manageMenus.refresh();
                });
    }

    private void batchSave(boolean realTime,Boolean finish) {
        if(!this.sheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的测评配合需求的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        var evaluationRequires = this.sheetView.getModifyData()
                .stream()
                .map(EvaluationRequireViewMapper.INSTANCE::toDTO)
                .toList();
        if (!realTime && CollectionUtils.isEmpty(evaluationRequires)) {
            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
            setFinishState(finish);
            return;
        }
        LogUtils.info(log, "批量测评配合需求信息...");
        LogUtils.record(log, "请求数据:{}", evaluationRequires);
        CompletableFuture.supplyAsync(() -> this.evaluationRequireService.batchSaveEvaluationRequires(evaluationRequires))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        queryEvaluationRequire();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        setFinishState(finish);
                    } else {
                        if(realTime){
                            log.error("即时保存测评配合需求信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量测评配合需求信息出错!", ex);
                    return null;
                });
    }

    private void setFinishState(boolean finish){
        FinishState state = finish ? FinishState.FINISH : FinishState.INCOMPLETE;
        CompletableFuture.supplyAsync(() -> evaluationRequireService.setEvaluationRequireFinishState(currentLayerTarget.getSystemId(),
                        currentLayerTarget.getTargetId(), currentLayerTarget.getName(), state))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshFinishState(state);
                    } else {
                        MessageDialog.builder()
                                .withType(MessageType.FAIL)
                                .withMessage(res.getMsg())
                                .withContainer(this.page)
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("设置测评进度信息出错!", ex);
                    return null;
                });
    }

}